package com.qf.mvc01.interceptor;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ProductInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        long startTime = System.currentTimeMillis();
        request.setAttribute("start",startTime);
        System.out.println("pre~~~");
        // 判断当前用户是不是登录过 ，约定登陆过的请求头中都会带有一个特殊的字段token
        String token = request.getHeader("token");
        if(token!=null){
            return true; //放行，后续的拦截器或handler就会执行
        }else {
            response.sendRedirect("/form.html");
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("post~~");
        Long start = (Long) request.getAttribute("start");
        long endTime = System.currentTimeMillis();
        System.out.println(endTime-start);

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("after~~");
    }
}
